//
//  CASVieController.m
//  UGuideUS
//
//  Created by Will Wang on 22/07/2012.
//  Copyright (c) 2012 UGuideUs. All rights reserved.
//

#import "CASVieController.h"
#import "AddCommentViewController.h"

@implementation CASVieController
@synthesize SFUComputinID=_SFUComputinID;
@synthesize password=_password;
@synthesize locationName;
@synthesize authResultMessage = _authResultMessage;

BOOL   isAuthenticated=FALSE;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //change navigation bar colour
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:172.0/255   
                                                                        green:04.0/255   
                                                                         blue:08.0/255   
                                                                        alpha:1];
    self.password.secureTextEntry=YES;
    NSLog(@"locationName=%@",self.locationName);
    
}

- (void)viewDidUnload
{
    [self setSFUComputinID:nil];
    [self setPassword:nil];
    [self setAuthResultMessage:nil];
    isAuthenticated=false;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)returnKeyboard : (id)sender {
    [sender resignFirstResponder];
}


/*  NAME:       prepareForSegue()
 *
 *  PURPOSE:    Allows another view to prepare for the sending of information from this view.
 */

- (void)prepareForSegue : (UIStoryboardSegue *)segue sender : (id)sender
{
    if ([segue.identifier isEqualToString : @"AddTheComment"]) 
    { 
        [segue.destinationViewController setUserNameContent:_SFUComputinID.text];
        [segue.destinationViewController setLocationNameContent:self.locationName];
    }
}

/*
 Attempt to authenticate and get a TGT from CAS server. Provide some static
 values for this test. Normally the username & password would come from user
 input and stored somewhere for use later.
 */
- (IBAction)authenticate:(UIButton *)sender {
        NSString *username = self.SFUComputinID.text;
        NSString *password = self.password.text;
        
        NSString *casServer = @"https://cas.sfu.ca/cgi-bin/WebObjects/cas.woa";
        NSString *casRestletPath = @"/tickets/";
        
        // Authenticate and get TGT
        NSLog(@"Authenticating...");
    
        [[CAS client] initWithCasServer:casServer
                            restletPath:casRestletPath
                               username:username
                               password:password
                        authCallbackObj:self
                   authCallbackSelector:@selector(authenticationDidFinishWithStatusCode:)];
    
        if(isAuthenticated==true){
//            NSLog(@"Prepare to send message");
            [self performSegueWithIdentifier:@"AddTheComment" sender:self];
//            //add another view, and pass username and location to it
//            AddCommentViewController *next=[[AddCommentViewController alloc]  
//                                           initWithNibName:nil bundle:nil];
//            
//            //init the username content and location name content
//            [next setUserNameContent:_SFUComputinID.text];
//            [next setLocationNameContent:self.locationName];
//            
//            [[self navigationController]
//             pushViewController:next animated:YES];
            
        }else{
          self.SFUComputinID.text=@"";
            self.password.text=@"";
        }
        
}


/*
 Callback for CAS authentication. Receives the HTTP status code given
 by CAS server and delegates action off to appropriate method.
 */
- (void) authenticationDidFinishWithStatusCode:(NSNumber *)statusNumber {
	int statusCode = [statusNumber intValue];
	
//	NSLog(@"Authentication Results: %i", statusCode);
	
	// Handle authentication success/failures here
	switch (statusCode) {
		case 201:
			[self authenticationSucceeded];
			break;
		case 400:
			[self authenticationFailed:@"Invalid credentials"];
			break;
		case 0:
			[self authenticationFailed:@"No connection available"];
			break;
		default:
			[self authenticationFailed:@"Encountered unknown status code"];
			break;
	}
}

/*
 Do something if the authentication is successful
 */
- (void) authenticationSucceeded {
	NSLog(@"Authentication succeeded!");
    isAuthenticated=true;
	[self.authResultMessage setText:@"Authentication succeeded!"];
}

/*
 Do something if the authentication fails
 */
- (void) authenticationFailed:(NSString *)reason {
	NSString *message = [NSString stringWithFormat:@"Authentication failed: %@", reason];	
    isAuthenticated=false;
	NSLog(@"%@", message);
	[self.authResultMessage setText:message];
}


@end
